package com.example.fragmentdemo.adapter;

import static androidx.constraintlayout.helper.widget.MotionEffect.TAG;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.MimeTypeMap;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.core.content.FileProvider;
import androidx.recyclerview.widget.RecyclerView;


import com.example.fragmentdemo.R;
import com.example.fragmentdemo.bean.FileBean;
import com.example.fragmentdemo.constant.Constant;
import com.example.fragmentdemo.player.MusicPlayerActivity;
import com.example.fragmentdemo.player.VideoPlayerActivity;
import com.example.fragmentdemo.utils.ToastUtil;

import java.io.File;
import java.util.ArrayList;
import java.util.List;


public class FileAdapter extends RecyclerView.Adapter<FileAdapter.MyViewHolder> implements View.OnClickListener {


    private List<FileBean> beanList=new ArrayList<>(); // 数据源
    private List<FileBean> currentList=new ArrayList<>(); // 当前显示的列表项
    private LayoutInflater layoutInflater;
    private Context context;
    private static FileBean bean;

    private static String sharePath;


    public FileAdapter(ArrayList<FileBean> list, Context context) {
        //两个方式的区别
        beanList=list;
        this.currentList.addAll(list);
        this.context = context;
        layoutInflater = LayoutInflater.from(context);
    }



    @SuppressLint("NotifyDataSetChanged")
    public void refreshData( ArrayList<FileBean> beanList){
        this.beanList=beanList;
        notifyDataSetChanged();
    }


    @NonNull
    @Override
    public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = View.inflate(context, R.layout.item_list, null);

        return new MyViewHolder(view);
    }


    @Override
    public void onBindViewHolder(@NonNull MyViewHolder holder, @SuppressLint("RecyclerView") int position) {
        // 清除旧数据
        holder.tv_name.setText("");
        holder.tv_path.setText("");
        holder.iv_img.setImageDrawable(null);
        holder.tv_time.setText("");
        bean = currentList.get(position);
        Log.d(TAG, "xiaoxulu: "+bean.getName());
        String path = bean.getPath();
        Log.d(TAG, "sharePath: "+sharePath);
        holder.setSharePath(path); // 设置sharePath的值
        holder.setFileName(bean.getName());
        holder.setLength(bean.getLength());
        holder.setTime(bean.getTime());
        String fileType = bean.getFileType();
        Log.d(TAG, "fileType: "+fileType);
        switch (fileType) {
            case "PDF":
                holder.iv_img.setImageResource(R.mipmap.pdf);
                break;
            case "PPT":
                holder.iv_img.setImageResource(R.mipmap.ppt);
                break;
            case "DOC":
                holder.iv_img.setImageResource(R.mipmap.doc);
                break;
            case "EXCEL":
                holder.iv_img.setImageResource(R.mipmap.excel);
                break;
            case "ETT":
                holder.iv_img.setImageResource(R.mipmap.ett);
                break;
            case "AUDIO":
                holder.iv_img.setImageResource(R.mipmap.mp3);
                holder.tv_time.setText(bean.getTime());
                break;
            case "VIDEO":
                holder.iv_img.setImageResource(R.mipmap.mp4);
                holder.tv_time.setText(bean.getTime());
                break;
            case "IMAGE":
                holder.iv_img.setImageResource(R.mipmap.image);
                break;
            default:
                break;
        }

        holder.tv_name.setText(bean.getName());
        holder.tv_path.setText(bean.getPath());
    }




    @Override
    public int getItemCount() {
        if (beanList.isEmpty()) {
            return 0;
        }
        return beanList.size();
    }

    @Override
    public void onClick(View v) {
    }


    public static class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
        TextView tv_name;
        TextView tv_path;
        ImageView iv_img;

        ImageView btn_detail;
        RelativeLayout relativeLayout;

        TextView tv_time;

        LinearLayout linearLayout;
        private String sharePath; // 添加sharePath字段

        private String fileName;

        private String length;

        private String time;

        public void setSharePath(String sharePath) {
            this.sharePath = sharePath;
        }

        public void setFileName(String fileName) {
            this.fileName = fileName;
        }

        public void setLength(String length) {
            this.length = length;
        }

        public void setTime(String time) {
            this.time = time;
        }

        public MyViewHolder(@NonNull View itemView) {
            super(itemView);
            tv_name = itemView.findViewById(R.id.tv_name);
            tv_path = itemView.findViewById(R.id.tv_path);
            iv_img = itemView.findViewById(R.id.iv_img);
            btn_detail = itemView.findViewById(R.id.btn_detail);
            tv_time = itemView.findViewById(R.id.tv_time);
            relativeLayout = itemView.findViewById(R.id.rl_container);
            linearLayout = itemView.findViewById(R.id.begin_audio);

            btn_detail.setOnClickListener(this);
            linearLayout.setOnClickListener(this);

            linearLayout.setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View v) {
                    Intent shareIntent = new Intent(Intent.ACTION_SEND);
                    String path=sharePath;
                    shareIntent.setType("text/plain");
                    File file = new File(path);
                    Uri contentUri = FileProvider.getUriForFile(iv_img.getContext(), Constant.AUTHORITY, file);
                    shareIntent.putExtra(Intent.EXTRA_STREAM, contentUri);
                    shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                    iv_img.getContext().startActivity(shareIntent);
                    return true;
                }
            });
        }

        @Override
        public void onClick(View v) {

            int position = getAdapterPosition();
            if (position != RecyclerView.NO_POSITION) {
                if (v.getId()==R.id.btn_detail) {
                        openDialog();
                } else if (v.getId()==R.id.begin_audio){
                    openFile(sharePath,fileName);
                }
            }
        }


        private  void openFile(String filePath,String fileName) {
            Intent intent;
            Log.d(TAG, "sharePath: "+filePath);
            File file = new File(filePath);
            if (file.exists()) {
                    if  (fileName.endsWith(".mp4")){
                        intent = new Intent(iv_img.getContext(), VideoPlayerActivity.class);
                        intent.putExtra("uri", filePath);
                        intent.putExtra("name", fileName);
                        iv_img.getContext().startActivity(intent);
                    } else if (fileName.endsWith(".mp3")) {
                        intent = new Intent(iv_img.getContext(), MusicPlayerActivity.class);
                        intent.putExtra("uri", filePath);
                        intent.putExtra("name", fileName);
                        intent.putExtra("time", time);
                        iv_img.getContext().startActivity(intent);
                    } else {
                        intent = new Intent(Intent.ACTION_VIEW);
                        Uri uri = FileProvider.getUriForFile(iv_img.getContext(), Constant.AUTHORITY, file);
                        intent.setDataAndType(uri, getMimeType(filePath));
                        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                        iv_img.getContext().startActivity(intent);
                    }




            } else {
                ToastUtil.toastShort(iv_img.getContext(), Constant.FILE_NOT_EXIST);
            }
        }

        // 获取文件的MIME类型
        private static String getMimeType(String filePath) {
            String mimeType = "*/*";
            String extension = MimeTypeMap.getFileExtensionFromUrl(filePath);
            if (extension != null) {
                mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
            }
            return mimeType;
        }


        @SuppressLint("SetTextI18n")
        public void openDialog() {
            // 创建AlertDialog.Builder对象
            View customView = LayoutInflater.from(tv_name.getContext()).inflate(R.layout.custom_dialog, null);
            ImageView dialogImage = customView.findViewById(R.id.dialog_image);
            TextView dialogMessage = customView.findViewById(R.id.dialog_message);

            // 设置对话框的图片和消息内容
            dialogImage.setImageDrawable(iv_img.getDrawable());
            dialogMessage.setText( "\n" +
                    Constant.FILE_NAME + tv_name.getText() + "\n" +
                    Constant.FILE_PATH + tv_path.getText() + "\n" +
                    Constant.CREATE_TIME + (bean.getCreateTime() != null ? bean.getCreateTime() : "") + "\n" +
                    Constant.UPDATE_TIME + (bean.getUpdateTime() != null ? bean.getUpdateTime() : "")+"\n"+
                    Constant.FILE_LENGTH+length+Constant.KB);

            dialogMessage.setPadding(30, 0, 0, 0);
            dialogMessage.setTextSize(15);

            // 创建AlertDialog并将自定义视图添加到其中
            AlertDialog.Builder builder = new AlertDialog.Builder(tv_name.getContext());
            builder.setTitle(Constant.DETAIL);
            builder.setView(customView);
            builder.setPositiveButton(Constant.YES, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                    dialog.dismiss(); // 关闭对话框
                    ToastUtil.toastShort(iv_img.getContext(), Constant.I_KNOW);
                }
            });
            AlertDialog dialog = builder.create();
            dialog.show();
        }


    }


}


